package com.fanketly.funacg2.ui.screen

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fanketly.funacg2.data.entity.conventToWork
import com.fanketly.funacg2.ui.components.SwipeToDelete
import com.fanketly.funacg2.ui.viewmodels.FavouriteViewModel
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator

@OptIn(ExperimentalFoundationApi::class)
@Destination
@Composable
fun FavouriteScreen(
    homeViewModel: HomeViewModel,
    favouriteViewModel: FavouriteViewModel,
    navigator: DestinationsNavigator,
) {
    val data = favouriteViewModel.pager.collectAsLazyPagingItems()
    Box(modifier = Modifier.fillMaxSize()) {
        if (data.loadState.refresh == LoadState.Loading) {
            androidx.compose.material3.LinearProgressIndicator(
                modifier = Modifier.fillMaxWidth()
            )
        } else LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 8.dp)
        ) {
            items(data.itemCount, key = data.itemKey { it.id }) { index ->
                val workEntity = data[index]
                if (workEntity != null) SwipeToDelete(
                    Modifier.animateItemPlacement(),
                    title = workEntity.title,
                    thumbnailCoverUrl = workEntity.thumbnailCoverUrl,
                    dismissedToEnd = homeViewModel::openDrawer,
                    onDelete = {
                        favouriteViewModel.cancelFavourite(workEntity.id)
                    }) {
                    homeViewModel.getAudio(workEntity.conventToWork())
                }
            }
        }
    }
}
